package com.ocom.payhandle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payhandle.dao.IDaoCompanyInfo;
import com.ocom.payhandle.service.CompanyInfoService;
import com.ocom.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


@Service
public class CompanyInfoServiceImpl extends ServiceImpl<IDaoCompanyInfo, EntityCompanyInfo> implements CompanyInfoService {

    @Value("${pay.url}")
    private String payCenterUrl;

    @Resource
    private RedisUtil redisUtil;

    private  static Map<Integer , String> payCenter = new HashMap(){
        {
            put(0, "http://127.0.0.1:8080/ocom_pay");
            put(1, "http://192.168.3.123:32880/ocom_pay");
            put(2, "http://192.168.185.142:33880/ocom_pay");
        }
    };

    /**获取单位信息*/
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "comId")
    @Override
    public EntityCompanyInfo GetCompanyInfo(Long comId) {
        QueryWrapper<EntityCompanyInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("com_id",comId);
        return this.getOne(wrapper);
    }


    @Override
    public String getPayCenterUrl(Long comId, String companyId) {

        if (comId == null) {
            return payCenter.get(0);
        }

        //2个单位迁不动 写死统一支付地址！ 2025年3月29日03:06:40
//        if(comId == 712l ){
//            return "http://47.120.6.231:8080/ocom_pay" ;
//        }


        Object payUrl = redisUtil.get("payCenter:#comId:"+comId+"#companyId:" + companyId);
        if (payUrl != null) return payCenter.get((Integer) payUrl);

        if (!payCenterUrl.equals("dev")) {
            if (companyId.length() > 0 && Character.isDigit(companyId.charAt(companyId.length() - 1))) {
                redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, 1, Long.valueOf(60 * 60 * 4));
                return payCenter.get(1);
            } else {
                companyId = companyId.toUpperCase(Locale.ROOT);
                char lastChar = companyId.charAt(companyId.length() - 1);
                int indexA = (int) lastChar;
                indexA -= 63;  //A -> 2 B->3 类推
                redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, indexA, Long.valueOf(60 * 60 * 4));
                return payCenter.get(indexA);
            }

        } else {
            redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, 0, Long.valueOf(60 * 60 * 4));
            return payCenter.get(0);
        }

    }

}
